package com.springboot.codeminestarter.codemine.filter;

import com.springboot.codeminestarter.codemine.exception.BusinessException;
import com.springboot.codeminestarter.codemine.tips.TipMess;
import com.springboot.codeminestarter.codemine.utils.JwtUtil;
import com.springboot.codeminestarter.codemine.utils.StringUtil;
import com.springboot.codeminestarter.codemine.wrapper.RedisWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

//@WebFilter("/*")
public class TokenFilter implements Filter {
    private Logger LOGGER = LoggerFactory.getLogger(TokenFilter.class);

    private static final Long TOKEN_LIFESPAN = 60*60*1000L;

    @Resource
    private RedisWrapper redisWrapper;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String accessToken = request.getHeader("accessToken");
        if (StringUtil.isEmpty(accessToken)) {
            chain.doFilter(request, servletResponse);
            return;
        }

        // 校验Token
        checkToken(accessToken);

        chain.doFilter(request, servletResponse);
    }

    /**
     * token校验，token是否有效，token是否过期
     */
    private void checkToken(String token) {

        Integer userId = JwtUtil.getClaim(token, "userId", Integer.class);
        Long expireTime = redisWrapper.getExpireTimeWithTimeUnit(userId, TimeUnit.HOURS);
        if (expireTime <= 0) {
            throw new BusinessException(TipMess.BASE_TOKEN_EXPIRE);
        }

        // 请求其他系统时，校验TOKEN， 有效期小于1小时进行续期
    }
}
